/**
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.api.adwords.starterkit.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Useful methods to deal with Data2String  
 * 
 * @author rodrigo.f.vale@gmail.com (Rodrigo Vale)
 */
public class DateString {

  /**
   * Convert a String to a Date
   *
   * @param date the string date
   * @param format the date format on the string
   * @return the date in Date format
   */
  public static Date string2Date(String date, String format) {
    DateFormat df = new SimpleDateFormat(format);
    try {
      return df.parse(date);
    } catch (ParseException e) {
      DumpExceptions.dumpException(e);
    }
    return null;
  }
  
  /**
   * Convert a String to a java.sql.date
   *
   * @param date the string date
   * @param format the string date format
   * @return the java.sql.date
   */
  public static java.sql.Date string2DateSQL(String date, String format) {
    return new java.sql.Date(string2Date(date, format).getTime());
  }

  /**
   * Converts a java.util.Date to java.sql.Date  
   */
  public static java.sql.Date date2DateSQL(Date date) {
    return new java.sql.Date(date.getTime());
  }

  /**
   * Converts a Date to String
   *
   * @param date the date
   * @param format the output format
   * @return the string
   */
  public static String date2String(Date date, String format) {
    SimpleDateFormat dateFormat = new SimpleDateFormat(format);
    return dateFormat.format(date);
  }

  /**
   * Converts a java.sql.Date to String
   *
   * @param date the date
   * @param format the output format
   * @return the string
   */
  public static String dateSQL2String(java.sql.Date date, String format) {
    SimpleDateFormat dateFormat = new SimpleDateFormat(format);
    return dateFormat.format(new Date(date.getTime()));
  }
}